const { render } = require('ejs');
var express = require('express');
var router = express.Router();
var { UserModel, MvModel, conModel } = require('../untils/model')
var { checkUsername, timeFormat } = require("../untils/index");
const { query } = require('express');
const { now } = require('mongoose');
//req  请求 res 响应
//res.render 渲染页面 ejs
//get get请求


/* GET home page. */
router.get('/index', function(req, res, next) { //首页

    res.render('index', {
        title: '超管后台管理系统',
        username: req.session.username,
    });
});

router.get("/chatroom", (req, res) => {
    checkUsername(req, res, (username) => {
        res.render("chatroom", { username })
    })
})


// router.get('/index', function(req, res, next) {
//     res.render('index', { title: '超管后台管理系统' });
// });


router.get("/login", (req, res) => { //登录
    res.render('login')
})

router.get('/register', (req, res) => { //注册
    res.render('register')
})



router.get("/leaveout", (req, res) => { //退出
    req.session.destroy(() => {
        res.redirect("/index")
    })
})

router.get("/movies", (req, res) => { //电影中心
    checkUsername(req, res, (username) => {
        MvModel.find({}, { _id: 0 }).then(result => {
            res.render("movies", { username, result })
        })
    })
})


router.get("/moviesyear", (req, res) => { //电影中心 排年份排序
    checkUsername(req, res, (username) => {
        MvModel.find({}, { _id: 0 }).sort({ year: 1 }).then(result => {
            res.render("moviesyear", { username, result })
        })
    })
})

router.get("/moviesserach", (req, res) => { //电影中心 模糊查询电影
    var mvname = req.query.mvname
    console.log(mvname)
    checkUsername(req, res, (username) => {
        MvModel.find({ title: { $regex: `${mvname}`, $options: 'i' } }, { _id: 0 }).then(result => {
            console.log(result)
            res.render("moviesserach", { username, result })
        })
    })
})


router.get("/moviesaverage", (req, res) => { //电影中心 评分排序
    checkUsername(req, res, (username) => {
        MvModel.find({}, { _id: 0 }).sort({ rating: -1 }).then(result => {
            res.render("moviesaverage", { username, result })
        })
    })
})

router.get("/detail", (req, res) => { // 电影详情
    var mid = req.query
    checkUsername(req, res, (username) => {
        MvModel.find({ id: mid.mid }, { _id: 0 }).then(result => {
            res.render("detail", { username, result, mid })
        })
    })
})

router.post("/conment", (req, res) => { //添加评论
    var text = req.body.text
    var id = req.body.id
    checkUsername(req, res, (username) => {
        MvModel.findOne({ id: id }).then(result => {
            conModel.insertMany({ cid: id, text: text, username: username, time: Date(), movie: result }).then(data => {
                res.json({
                    code: 200,
                    type: 1,
                    msg: "评论成功"
                })
            })
        })
    })
})

router.get("/allcom", (req, res) => { //评论中心
    checkUsername(req, res, (username) => {
        var query = req.query;
        var page = query.page ? query.page * 1 : 1;
        var pageSize = query.pageSize * 1 || 10;
        var total = 0;
        var totalPage = 0;

        conModel.find({}).then(result => {
            total = result.length
            totalPage = Math.ceil(total / pageSize)
            page = page < 1 ? 1 : page;
            page = page > totalPage ? totalPage : page
            conModel.find({}).skip((page - 1) * pageSize).limit(pageSize).sort({ time: -1 }).then(result => {
                result = result.map(item => {
                    return {...item._doc, time: timeFormat(item.time) }
                })
                res.render("allcom", { username, result, page, pageSize, total, totalPage })
            })
        })
    })
})


router.get("/removeone", (req, res) => {
    checkUsername(req, res, username => {
        var { _id } = req.query;
        conModel.remove({
                _id
            })
            .then(result => {
                res.json({
                    code: 200,
                    result,
                    msg: '删除成功'
                })
            })
    })
})



router.post("/updateone", (req, res) => {
    checkUsername(req, res, username => {
        var { _id, title, content } = req.body;
        conModel.updateMany({
                _id
            }, {
                $set: {
                    text: content,
                    time: new Date()
                }
            })
            .then(result => {
                res.json({
                    code: 200,
                    result,
                    msg: '修改成功'
                })
            })
    })
})


router.post("/checkcon", (req, res) => {
    var id = req.body.id
    console.log(id)
    checkUsername(req, res, (usernmae) => {
        conModel.find({ cid: id }).sort({ time: -1 }).then(result => {
            res.json({
                code: 200,
                type: 1,
                msg: "查询成功",
                result: result
            })
        })
    })
})


router.get("/mine", (req, res) => {
    // res.render("mine")
    if (req.session.username) {
        UserModel.findOne({ usernames: req.session.username }).then(result => {
            res.render('mine', { username: req.session.username, result })
        })
    }
})



router.get('/myname', (req, res) => {
    res.json({
        code: 200,
        msg: "获取信息成功",
        path: req.path,
        query: req.query,
        result: []
    })
})

router.get('/test/:uid?', (req, res) => {
    res.json({
        code: 200,
        msg: "获取信息成功",
        query: req.query,
        params: req.params
    })
})

router.post('/upfile', (req, res) => {
    res.json({
        code: 200,
        msg: "获取信息成功",
        query: req.query,
        params: req.params
    })
})

var multiparty = require("multiparty")
var fs = require("fs")
    // 上传图片  
router.post("/uploadImg", (req, res) => {
    const form = new multiparty.Form(); // 自定义表单对象  
    form.encoding = "utf-8"
    form.uploadDir = "./uploadtemp" // 临时文件中转站
    form.maxFilesSize = 8 * 1024 * 1024; // 8M 
    form.parse(req, function(err, fields, files) {
        if (err) {
            console.log(err)
            res.send("<script>alert('图片过大,请重新上传');location.reload()'</script>")
        }
        var uploadUrl = "/images/upload/",
            file = files['filedata'], // 图片信息
            originalFilename = file[0].originalFilename, // 文件名  2.jpg 
            tempath = file[0].path;
        var timestamp = new Date().getTime(); // 时间戳  为了避免图片名字冲突 
        uploadUrl += timestamp + originalFilename; // 1.jpg ==> 15112341231.jpg
        var newPath = "./public" + uploadUrl; // 最后路径 
        var fileRead = fs.createReadStream(tempath); // 可读流 
        var fileWrite = fs.createWriteStream(newPath); // 可写流  
        fileRead.pipe(fileWrite);
        fileWrite.on("close", () => {
            fs.unlinkSync(tempath); // 上传成功把中转站的文件删除 
            res.json({
                err: "",
                msg: uploadUrl
            })
        })
    })
})





module.exports = router;